# -*- coding: utf-8 -*-
import requests
import time
from hg import HGA
from datetime import datetime
import pytz
from fuzzywuzzy import fuzz

def similarity(match1, match2):
    """
            计算相似度。数值0-100，我们按照80计算,返回true
    """
    return fuzz.ratio(match1, match2) > 70

def fetch_match_data(page=1):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    url = f"http://160.30.209.85:8000/matchs/?page={page}"

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return []


def print_info(info):
    current_time = datetime.now()
    print(f'{current_time.strftime("%m-%d %H:%M:%S")}   {info}')

def get_recent():
    start_page = 1
    end_page = 3  # 根据实际需要调整
    all_match = []
    for page in range(start_page, end_page + 1):
        data = fetch_match_data(page)
        for match in data:
            """
            print(match)
            print("比赛信息：")
            print(f"联赛: {match['league']}")
            print(f"主队: {match['home']} vs 客队: {match['away']}")
            print(f"预测结果: {match['prediction']}")
            print(f"随机码: {match['random']}")
            print("------------------------")
            print(time.time()*1000 - match['start_time'])
            print(time.time())
            print(match['start_time'])
            """
            if time.time()*1000 - match['start_time'] < 3*60*1000:
                all_match.append(match)
            else:
                return all_match
        time.sleep(1)  # 添加延时避免请求过快


def celv1():
    hg = HGA()
    hg.findver()
    time.sleep(5)
    hg.login()
    time.sleep(5)
    hg.today()

    another_set = set([])
    while True:
        try:
            all_match = get_recent()
            print_info("======================")
            for match in all_match:
                match_name = f"{match['home']} - {match['away']}"
                if match_name in another_set:
                    continue
                else:
                    hg.check_login()
                    sports = hg.today()
                    for sport in sports:
                        if similarity(sport.match, match_name) and sport.start_time == match['start_time']:
                            print_info(f'匹配hg={sport.match}')
                            if 'Over 2.5' == match['prediction'] or 'Over 2.75' == match['prediction']:
                                print_info(f'匹配到2.5或2.75盘口={sport.match}')
                                hg.check_login()
                                some = hg.pkdata(sport.sport_id, 'OU', 'C')
                                flag = hg.bet(sport.sport_id, 'OU', 'C', 50, some[1], some[2], some[3])
                                if flag:
                                    another_set.add(match_name)
                                    time.sleep(10)
                                else:
                                    time.sleep(5)
                                    print_info(f"下注重试一次")
                                    some = hg.pkdata(sport.sport_id, 'OU', 'C')
                                    flag = hg.bet(sport.sport_id, 'OU', 'C', 50, some[1], some[2], some[3])
                                    another_set.add(match_name)
            time.sleep(15)
        # except ZeroDivisionError as e:
        except Exception as e:
            # print("Response Text:", response.text)
            print_info(f"请求过程中发生错误：{e}")

def is_goodnight() -> bool:
    """判断当前北京时间是否处于21:56至次日05:01（含21:56，不含05:01）"""
    beijing_tz = pytz.timezone('Asia/Shanghai')
    current_time = datetime.now(beijing_tz)
    hour = current_time.hour
    minute = current_time.minute
    total_minutes = hour * 60 + minute
    start = 21 * 60 + 56  # 21:56 = 1316 分钟
    end = 5 * 60 + 1     # 05:01 = 301 分钟
    return total_minutes >= start or total_minutes < end

def celv2():
    """
    按照时间来
    :return:
    """
    hg = HGA()
    hg.findver()
    time.sleep(5)
    hg.login()
    time.sleep(5)
    hg.today()

    another_set = set([])
    while True:
        if is_goodnight():
            try:
                all_match = get_recent()
                print_info("======================")
                for match in all_match:
                    match_name = f"{match['home']} - {match['away']}：{match['prediction']}"
                    if match_name in another_set:
                        continue
                    else:
                        hg.check_login()
                        sports = hg.today()
                        for sport in sports:
                            if similarity(sport.match, f"{match['home']} - {match['away']}") and sport.start_time == match['start_time']:
                                print_info(f'匹配hg={sport.match}')
                                if match['prediction'].startswith("Over"):
                                    print_info(f'匹配到2.5或2.75盘口={sport.match}')
                                    hg.check_login()
                                    some = hg.pkdata(sport.sport_id, 'OU', 'C')
                                    flag = hg.bet(sport.sport_id, 'OU', 'C', 50, some[1], some[2], some[3])
                                    if flag:
                                        another_set.add(match_name)
                                        time.sleep(10)
                                    else:
                                        time.sleep(5)
                                        print_info(f"下注重试一次")
                                        some = hg.pkdata(sport.sport_id, 'OU', 'C')
                                        flag = hg.bet(sport.sport_id, 'OU', 'C', 50, some[1], some[2], some[3])
                                        another_set.add(match_name)
                                if match['prediction'].startswith("Under"):
                                    print_info(f'匹配到小球={sport.match}')
                                    hg.check_login()
                                    some = hg.pkdata(sport.sport_id, 'OU', 'H')
                                    flag = hg.bet(sport.sport_id, 'OU', 'H', 50, some[1], some[2], some[3])
                                    if flag:
                                        another_set.add(match_name)
                                        time.sleep(10)
                                    else:
                                        time.sleep(5)
                                        print_info(f"下注重试一次")
                                        some = hg.pkdata(sport.sport_id, 'OU', 'H')
                                        flag = hg.bet(sport.sport_id, 'OU', 'H', 50, some[1], some[2], some[3])
                                        another_set.add(match_name)
                                if match['prediction'].startswith("Home"):
                                    print_info(f'匹配到主队={sport.match}')
                                    hg.check_login()
                                    some = hg.pkdata(sport.sport_id, 'R', 'H')
                                    flag = hg.bet(sport.sport_id, 'R', 'H', 50, some[1], some[2], some[3])
                                    if flag:
                                        another_set.add(match_name)
                                        time.sleep(10)
                                    else:
                                        time.sleep(5)
                                        print_info(f"下注重试一次")
                                        some = hg.pkdata(sport.sport_id, 'R', 'H')
                                        flag = hg.bet(sport.sport_id, 'R', 'H', 50, some[1], some[2], some[3])
                                        another_set.add(match_name)
                                if match['prediction'].startswith("Away"):
                                    print_info(f'匹配到客队={sport.match}')
                                    hg.check_login()
                                    some = hg.pkdata(sport.sport_id, 'R', 'C')
                                    flag = hg.bet(sport.sport_id, 'R', 'C', 50, some[1], some[2], some[3])
                                    if flag:
                                        another_set.add(match_name)
                                        time.sleep(10)
                                    else:
                                        time.sleep(5)
                                        print_info(f"下注重试一次")
                                        some = hg.pkdata(sport.sport_id, 'R', 'C')
                                        flag = hg.bet(sport.sport_id, 'R', 'C', 50, some[1], some[2], some[3])
                                        another_set.add(match_name)
                time.sleep(15)
            # except ZeroDivisionError as e:
            except Exception as e:
                # print("Response Text:", response.text)
                print_info(f"请求过程中发生错误：{e}")
        else:
            time.sleep(20)
            print_info(f"非交易时间")


if __name__ == "__main__":
    celv2()